package com.zhongxi.guoyuan.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.GvSlidingAdapter;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.adapter.ad.JDViewAdapter;
import com.zhongxi.guoyuan.adapter.beautifulStore.ProjectAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.entity.service.ServiceItemData;
import com.zhongxi.guoyuan.entity.service.ServiceResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.ad.JDAdverView;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainStoreFragment extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {

    private List<HotGoodsData> datas = new ArrayList<HotGoodsData>();
    private String id = "0";
    private ViewFlow mViewFlow;
    private ImageBannerAdapter mBannerAdapter;

    private List<ProjectItemData> TITLES = new ArrayList<ProjectItemData>();
    private List<ServiceItemData> list = new ArrayList<ServiceItemData>();
    private RelativeLayout relaLayout;
    private int scrollHeight;
    private MyScrollView myScrollView;
    private RelativeLayout scrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private boolean isMeasured;

    private ImageView iv_search;
    private Spinner spinner;
    private String type;
    private EditText et_search;
    private NoScrollGridView gvList;
    private ProjectAdapter adapter;
    private NoScrollListView lvList;
    private ServiceResult serviceResult;
    private GvSlidingAdapter gvAdapter;
    private Map<String, String> map = new HashMap<>();
    private String status = "1";

    private boolean flag = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main_store, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("我的美容院");
        TITLES.add(new ProjectItemData("0", "全部", ""));

        //实现上拉布局悬停
        initScrollPause();

        iv_search = (ImageView) getView().findViewById(R.id.iv_search);
        et_search = (EditText) getView().findViewById(R.id.et_search);
        lvList = (NoScrollListView) getView().findViewById(R.id.lvList);

        //设置轮播图片高度
        FrameLayout flow = (FrameLayout) getView().findViewById(R.id.flow);
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);

        //筛选
        order();

    }

    private void upAndDown(List<HotGoodsData> data) {
        if(null!=data&&data.size()>0){
            datas.addAll(data);
        }
        final JDViewAdapter adapter = new JDViewAdapter(context, datas, 0);
        final JDAdverView tbView = (JDAdverView) getView().findViewById(R.id.jdadver);
        tbView.setAdapter(adapter);
        //开启线程滚动
        tbView.start();
    }

    private void order() {
        //智能排序
        spinner = (Spinner) getView().findViewById(R.id.spinner);
        ArrayAdapter<String> spAdapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item);
        List<String> spList = new ArrayList<String>();
        spList.add("时间倒序");
        spList.add("价格正序");
        spList.add("价格倒序");
        spAdapter.addAll(spList);
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                status = position+1+"";
                pageNum = 1;
                if(flag) {
                    getService();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 上拉悬停
     */
    private void initScrollPause() {
        //滑动置顶
        scrollBody = (RelativeLayout) getView().findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) getView().findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) getView().findViewById(R.id.linearStop);
        myScrollView = (MyScrollView) getView().findViewById(R.id.myScrollView);

        relaLayout = (RelativeLayout) getView().findViewById(R.id.relaLayout);
        ViewTreeObserver observer = relaLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    scrollHeight = relaLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });

        gvList = (NoScrollGridView) getView().findViewById(R.id.gvList);

    }

    private void lunbo(List<AdData> data) {
        //初始化轮播控件
        mViewFlow = (ViewFlow) getView().findViewById(R.id.viewflow);
        CircleIndicator mViewIndic = (CircleIndicator) getView().findViewById(R.id.viewflowdic);
        mViewFlow.setFlowIndicator(mViewIndic);

        if (data.size() > 0)
            mViewFlow.setSideBuffer(data.size()); // 实际图片数量
        if (mBannerAdapter == null) {
            mBannerAdapter = new ImageBannerAdapter(getActivity(), data);
            mViewFlow.setAdapter(mBannerAdapter);
        } else {
            mBannerAdapter.replaceAll(data);
        }
        mViewFlow.startAutoFlowTimer();
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new ProjectAdapter(context, list);
        lvList.setAdapter(adapter);
        //获取广告轮播
        getAds();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        myScrollView.setOnScrollListener(this);
        iv_search.setOnClickListener(this);
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long lon) {
                if (scrollBody.getParent() != linearBegin) {
                    myScrollView.scrollTo(0,0);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                id = TITLES.get(position).getId();  //项目id指哪类项目
                pageNum = 1;
                gvAdapter.setSelectIndex(position);
                gvAdapter.notifyDataSetChanged();
                id = TITLES.get(position).getId();
                getService();
            }
        });
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Intent intent = new Intent(context, ProjectDetailActivity.class);
                    intent.putExtra("id", list.get(position).getId());
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.iv_search:
                if (TextUtils.isEmpty(et_search.getText().toString().trim())) {
                    showShortToast("搜索不能为空");
                } else {
                    map.clear();
                    pageNum = 1;
                    map.put("content", et_search.getText().toString().trim());
                    String str = "&page="+pageNum;
                    type = "getService";
                    getServer(Url.INNER_SERVICE, map, str, false, null, "post");
                    et_search.setText("");
                }
                break;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= scrollHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (!MyTextUtils.isFastDoubleClick()) {
            pageNum++;
            getService();
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("showads".equals(type)) {
                AdResult adResult = gson.fromJson(response, AdResult.class);
                MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                if(adResult.getData().size()>0)
                    lunbo(adResult.getData());
                getRecommandService();
            } else if ("hotService".equals(type)) {
                HotGoodsResult hotServiceResult = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(hotServiceResult.getSafeobj());
//                Toast.makeText(context, "推荐服务", Toast.LENGTH_SHORT).show();
                if(hotServiceResult.getData().size()>0)
                    upAndDown(hotServiceResult.getData());
                getItem();
            } else if ("getItem".equals(type)) {
                ProjectItemResult itemResult = gson.fromJson(response, ProjectItemResult.class);
                if(null!=itemResult.getData()&&itemResult.getData().size()>0){
//                    TITLES = itemResult.getData();
                    TITLES.addAll(itemResult.getData());
                }
                MyApplication.getInstance().setSpValue(itemResult.getSafeobj());
                gvAdapter = new GvSlidingAdapter(context, TITLES);
                gvList.setAdapter(gvAdapter);
                setGvParams(gvList, TITLES, 5);
                getService();
            } else if ("getService".equals(type)) {
                serviceResult = gson.fromJson(response, ServiceResult.class);
                MyApplication.getInstance().setSpValue(serviceResult.getSafeobj());
                if (pageNum == 1) {
                    list.clear();
                }
                if (null != serviceResult.getData() && !"".equals(serviceResult.getData())) {
                    list.addAll(serviceResult.getData());
                }
                adapter.notifyDataSetChanged();
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置gridView的属性
    private void setGvParams(NoScrollGridView gv, List list, int item) {
        int spaceWith = CommonTool.dip2px(context, 10);//左边距 paddingLeft
        int with = getResources().getDisplayMetrics().widthPixels / item;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(list.size() * with, LinearLayout.LayoutParams.WRAP_CONTENT);
        gv.setLayoutParams(params);
        gv.setColumnWidth(with - spaceWith);
        gv.setHorizontalSpacing(spaceWith);
        gv.setStretchMode(GridView.NO_STRETCH);   //不拉伸
        gv.setOverScrollMode(0);
        gv.setNumColumns(list.size());      //一排显示几列
    }

    /**
     * 获取广告展示
     */
    private void getAds() {
        type = "showads";
        String getStr = "&type=2";
        getServer(Url.SHOW_ADS, null, getStr, false, null, "get");
    }

    /**
     * 获取推荐服务
     */
    private void getRecommandService() {
        type = "hotService";
        getServer(Url.HOT_SERVICE, null, "", false, null, "get");
    }

    /**
     * 获取项目列表
     */
    private void getItem() {
        type = "getItem";
        getServer(Url.ITEM_LIST, null, "", false, null, "get");
    }

    /**
     * 获取服务列表
     */
    private void getService() {
        type = "getService";
        String getStr = "&page=" + pageNum + "&itemid=" + id+"&orderby="+status;
        getServer(Url.SERVICE_LIST, null, getStr, false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                MyApplication.getInstance().setSpValue(result.getSafeobj());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}